package org.jeecg.modules.aliyun.phone.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.aliyun.phone.service.IPhoneService;
import org.jeecg.modules.aliyun.phone.service.ITaskService;
import org.jeecg.modules.demo.entity.Demo;
import org.jeecg.modules.demo.mapper.DemoMapper;
import org.jeecg.modules.phone.entity.*;
import org.jeecg.modules.phone.enums.TaskEnums;
import org.jeecg.modules.phone.mapper.*;
import org.jeecg.modules.phone.service.IPhoneAccountTaskService;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import wiremock.org.eclipse.jetty.util.StringUtil;

import java.util.List;

import static java.lang.Thread.sleep;

/**
 * @Description: DemoDescript
 * @Author: jeecg-boot
 * @Date:   2022-08-09
 * @Version: V1.0
 */
@Service
public class TaskServiceImpl extends ServiceImpl<DemoMapper, Demo> implements ITaskService {

    @Autowired
    private PhoneAccountTaskMapper phoneAccountTaskMapper;
    @Autowired
    PhoneAccountMapper phoneAccountMapper ;
    @Autowired
    PhoneAccountLogMapper phoneAccountLogMapper;
    @Autowired
    PhoneInstancesMapper phoneInstancesMapper;

    @Autowired
    PhoneTaskMapper phoneTaskMapper;
    @Autowired
    IPhoneService phoneService;
    @Autowired
    IPhoneAccountTaskService phoneAccountTaskService;

    @Override
    public String doRunCommand(String InstanceIds, String commandStr)   {
        return "";
    }

    @Value("${server.name}")
    private String  serverName;

    @Override
    public String taskCheck()   {
//        定时任务检查是否出发任务,本账户里按照 系统 母，子任务进行
//        获取本部门ID， 查找本部门ID的任务。保证自己的账户执行自己的任务。并按开始时间执行。
//        如果是-p手机任务可以同步执行。其他的系统任务需要独占运行。

        List<PhoneAccountTask> taskList = phoneAccountTaskService.list(new QueryWrapper<PhoneAccountTask>()
                .eq("task_status", TaskEnums.TaskStatus.WAIT.getName())
                .eq("create_by",serverName)
        );


//
//        taskList.forEach(v->{
////            这里有逻辑，如果系统任务，母任务就直接执行。
////            如果是子任务，要确保该ID没有正在执行的母任务。
//            PhoneTask phoneTask = phoneTaskMapper.selectById(v.getTaskId());
//            if(phoneTask.getTaskType().equals(TaskEnums.TaskType.ZI.getName())){
////                检查是否有母号任务
//                List<PhoneAccountTaskJoinTaskVo> phoneAccountTaskJoinTaskVos = phoneAccountTaskMapper.PhoneAccountTask_PhoneTask(new QueryWrapper<PhoneAccountTaskJoinTaskVo>()
//                        .and(i->i.eq("a.task_status", TaskEnums.TaskStatus.WAIT.getName())
//                                .or().eq("a.task_status", TaskEnums.TaskStatus.RUN.getName()))
//                        .eq("t.task_type", TaskEnums.TaskType.MU.getName())
//                        .eq("a.account_id",v.getAccountId())
//                );
//                if (phoneAccountTaskJoinTaskVos.size()==0){
//                    doPhoneTaskById(v,phoneTask);
//                }
//
//            }else{
//                doPhoneTaskById(v,phoneTask);
//            }
//
//        });
        return "";
    }

    private void doPhoneTaskById(PhoneAccountTask v,PhoneTask phoneTask) {
        System.out.println("发现待执行任务，开始执行."+ v.getTaskId());
//        设置执行中
        phoneAccountTaskMapper.updateById(v.setTaskStatus(TaskEnums.TaskStatus.RUN.getName()));
//        登录盘前段任务
        if(phoneTask.getId().equals(TaskEnums.TaskCode.LOGINP1ID.getName())){
            String runResult = loginPart1(v);
            System.out.println(runResult);
        }

//        if(phoneTask.getId().equals(TaskEnums.TaskCode.LOGINP2ID.getName())){
//            String runResult = loginPart2(v);
//            System.out.println(runResult);
//        }

        if(phoneTask.getId().equals(TaskEnums.TaskCode.GLJ.getName())){
            String runResult = guaLianjie(v);
            System.out.println(runResult);
        }

//        if(phoneTask.getId().equals(TaskEnums.TaskCode.XXL.getName())){
////            子号任务2
//            String runResult = guaLianjie(v);
//            System.out.println(runResult);
//        }
//
//        if(phoneTask.getId().equals(TaskEnums.TaskCode.XXL.getName())){
////            子号任务2
//            String runResult = guaLianjie(v);
//            System.out.println(runResult);
//        }

        if(phoneTask.getId().equals(TaskEnums.TaskCode.XXL.getName())){
//            子号任务2
            String runResult = clickXCX(v);
            System.out.println(runResult);
        }

        if(phoneTask.getId().equals(TaskEnums.TaskCode.ADD_DEVICE.getName())){
//            注册实体机
            String runResult = clickAddDevice(v);
            System.out.println(runResult);
        }




//        if(phoneTask.getId().equals(TaskEnums.TaskCode.LOGINP1ID.getName())){
//            String runResult = loginPart1(v);
//            System.out.println(runResult);
//        }
//
//        if(phoneTask.getId().equals(TaskEnums.TaskCode.LOGINP1ID.getName())){
//            String runResult = loginPart1(v);
//            System.out.println(runResult);
//        }


    }

    @Override
    public String loginPart1(PhoneAccountTask phoneAccountTask)   {

//        更新任务状态为运行中
        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setTaskStatus(TaskEnums.TaskStatus.RUN.getName()));
        PhoneAccount phoneAccount = phoneAccountMapper.selectOne(
                new QueryWrapper<PhoneAccount>()
                        .eq("id", phoneAccountTask.getAccountId())
        );
        phoneAccountLogInsert("开始创建" + phoneAccount.getPhoneNo() + "的登录盘",phoneAccountTask);


//        if(1>0){return "";}


//        创建手机实例
        String instances = phoneService.doRunInstances(new PhoneOrderPamarsVo()
                .setAmount(1)
                .setImageId("cpm-bp14thtbvv8k0u6uqm9p")
                .setChargeType("PostPaid")
                .setDescription("T" + phoneAccount.getPhoneNo() + "的登录盘")
                .setInstanceName("T" + phoneAccount.getPhoneNo() + "LoginImg")
                .setInstanceType("ecp.ce.large")
                .setKeyPairName("homePhone")
                .setRegionId("cn-hangzhou")
                .setSecurityGroupId("sg-bp1ggdbov2o3nvybkoey")
                .setVSwitchId("vsw-bp1f5diq3vbh9dw4frryq")
        );
        String instanceId = JSON.parseObject(instances).getJSONObject("instanceIds")
                .getJSONArray("instanceId").get(0).toString();
        phoneAccountLogInsert("购买云手机实例完成，实例启动中...",phoneAccountTask);

//        添加创建的实例到实例表
        PhoneInstances phoneInstances = new PhoneInstances().setInstanceId(instanceId) ;
        phoneInstancesMapper.insert(phoneInstances);

//		等待实例启动，并操作到验证码停止。并弹出验证码的界面

        String ipAddress = "未获取";
        for (int i = 0; i < 10; i++) {
            Result<Object> error = getObjectResult(3000);
            if (error != null){
                phoneAccountLogInsert("等三秒抛出异常",phoneAccountTask);
                break;
            }
            ipAddress = getIpAddress(phoneAccountTask, instanceId, i);
            if(!(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取") )  ){
                break;
            }
        }
//		10次30秒后还是没获取到IP结束。
        if(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取")){
            phoneAccountLogInsert("获取EIP失败.开始回滚...",phoneAccountTask);
            phoneService.doDeleteInstances(instanceId);
            phoneAccountLogInsert("创建登录盘失败",phoneAccountTask);

            phoneAccountTaskMapper.updateById(phoneAccountTask
                    .setTaskStatus(TaskEnums.TaskStatus.FAIL.getName()));
            return   "未获取到IP，请手动检查"   ;
        }
        phoneInstancesMapper.updateById(phoneInstances.setIpAddr(ipAddress));
        System.out.println(phoneInstances.getIpAddr());

        sleepSecond(40000,phoneAccountTask);
        phoneAccountLogInsert("开始启动抖音",phoneAccountTask);

//		并操作到验证码停止。并弹出验证码的界面
        String cmdStr ="am start com.ss.android.ugc.aweme/.main.MainActivity";
        String runCommandResult = phoneService.doRunCommand(instanceId, cmdStr);
        System.out.println(runCommandResult);


        doCommand(15000,"input tap 350 1120","点击青少年通知",instanceId);
        doCommand(10000,"input tap 655 1153","点击我的",instanceId);

        doCommand(7000,"input tap 80 573","切换密码登录",instanceId);
        doCommand(7000,"input tap 195 261","点击账户",instanceId);
        doCommand(1500,"input text " + phoneAccount.getDouAccount() ,"输入账户",instanceId);
        doCommand(1500,"input tap 195 343","点击密码",instanceId);
        doCommand(1500,"input  text " + phoneAccount.getDouPassword() ,"输入抖音密码",instanceId);
        doCommand(1500,"input tap 63 403","点击同意协议",instanceId);
        doCommand(1500,"input tap 353 513","点击登录",instanceId);

        phoneAccountLogInsert("正在发送短信验证，请注意手机查收",phoneAccountTask);
        doCommand(1500,"input tap 205 360","点击发送验证码",instanceId);
        phoneAccountLogInsert("输入短信验证码",phoneAccountTask);
        doCommand(60000,"input tap 99 360" ,"点击验证码狂",instanceId);

        phoneAccount = phoneAccountMapper.selectOne(
                new QueryWrapper<PhoneAccount>()
                        .eq("id", phoneAccountTask.getAccountId())
        );
        doCommand(1000,"input text  " + phoneAccount.getMaoPassword() ,"输入验证码",instanceId);

        doCommand(1500,"input tap 365 495","点击登录",instanceId);
        doCommand(3500,"input tap 463 715","点击去核对",instanceId);


        phoneAccountLogInsert("登录抖音完成，截图中",phoneAccountTask);
        doCommand(10000,"screencap -p /sdcard/screen.png","截图",instanceId);
        sleepSecond(6000,phoneAccountTask);
        String url1 ="screen/"+ phoneAccount.getPhoneNo() +"/" +System.currentTimeMillis() +".png";
        phoneService.doFetchFile(instanceId,  url1,"/sdcard/screen.png");
        phoneAccountLogInsert("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url1,phoneAccountTask);
        doCommand(1000,"rm /sdcard/screen.png -f","删除截图",instanceId);

        doCommand(1000,"am force-stop com.ss.android.ugc.aweme","关闭抖音",instanceId);
        phoneAccountLogInsert("打开抖猫",phoneAccountTask);
//     打开抖猫
        doCommand(6000,"input keyevent  3","按home",instanceId);
        doCommand(6000,"input swipe 300 800 300 80","上滑动",instanceId);
        doCommand(6000,"input tap 489 219","点击逗猫",instanceId);

        doCommand(6000,"input tap 150 589","点击账户",instanceId);
        doCommand(6000,"input text  " + phoneAccount.getMaoAccount() ,"输入账户",instanceId);
        phoneAccountLogInsert("正在发送短信验证，请注意手机查收",phoneAccountTask);
        doCommand(6000,"input tap 615 720","点击发短信按钮",instanceId);
        phoneAccountLogInsert("输入短信验证码",phoneAccountTask);
        doCommand(60000,"input tap 131 720","点击发短信狂",instanceId);
        phoneAccount = phoneAccountMapper.selectOne(
                new QueryWrapper<PhoneAccount>()
                        .eq("id", phoneAccountTask.getAccountId())
        );
        doCommand(2000,"input text  " + phoneAccount.getMaoPassword() ,"输入验证码",instanceId);
        doCommand(6000,"input tap 625 1153","点击下一bu",instanceId);
        doCommand(6000,"input tap 365 875","点击登录",instanceId);

        phoneAccountLogInsert("登录抖猫完成，截图中",phoneAccountTask);
        String url2 ="screen/"+ phoneAccount.getPhoneNo() +"/" +System.currentTimeMillis() +".png";
        doCommand(5000,"screencap -p /sdcard/screen.png","截图",instanceId);
        sleepSecond(3000,phoneAccountTask);
        phoneService.doFetchFile(instanceId,     url2,"/sdcard/screen.png");
        doCommand(10000,"rm /sdcard/screen.png -f","删除截图",instanceId);
        phoneAccountLogInsert("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url2,phoneAccountTask);

        doCommand(5000,"am force-stop com.doutui.bozhong","关闭抖猫",instanceId);
        sleepSecond(10000,phoneAccountTask);
//        https://cloudphone.console.aliyun.com/?_console_base_disable_=TOP~TOOLKIT#/connectWebRTC?instanceId=cp-bp112zfukuketxa7k7rg&regionId=cn-hangzhou



        phoneAccountLogInsert("开始保存登录盘",phoneAccountTask);

        String imageResult = phoneService.doCreateImage(new CreateImgPamarsVo()
                .setInstanceId(instanceId)
                .setRegionId("cn-hangzhou")
                .setImageName("T" + phoneAccount.getPhoneNo())
                .setDescription("T" + phoneAccount.getPhoneNo() + "LoginImg")
        );
        String imageId = JSON.parseObject(imageResult).getString("imageId");
        phoneAccount.setImgId(imageId);
        phoneAccountMapper.updateById(phoneAccount);
        phoneAccountLogInsert("保存登录盘完成，ID:" + imageId ,phoneAccountTask);

        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setTaskStatus(TaskEnums.TaskStatus.COMPLETED.getName()));
        return "";
    }





    @Override
    public String guaLianjie(PhoneAccountTask phoneAccountTask)   {

        PhoneAccount phoneAccount = phoneAccountMapper.selectOne(
                new QueryWrapper<PhoneAccount>()
                        .eq("id", phoneAccountTask.getAccountId())
        );

//        创建手机实例
        String instances = phoneService.doRunInstances(new PhoneOrderPamarsVo()
                .setAmount(1)
                .setImageId(phoneAccount.getImgId())
                .setChargeType("PostPaid")
                .setDescription("T" + phoneAccount.getPhoneNo() + "的glj盘")
                .setInstanceName("T" + phoneAccount.getPhoneNo() + "glj")
                .setInstanceType("ecp.ce.large")
                .setKeyPairName("homePhone")
                .setRegionId("cn-hangzhou")
                .setSecurityGroupId("sg-bp1ggdbov2o3nvybkoey")
                .setVSwitchId("vsw-bp1f5diq3vbh9dw4frryq")
        );
        String instanceId = JSON.parseObject(instances).getJSONObject("instanceIds")
                .getJSONArray("instanceId").get(0).toString();
        phoneAccountLogInsert("购买云手机实例完成，实例启动中...",phoneAccountTask);

//        添加创建的实例到实例表
        PhoneInstances phoneInstances = new PhoneInstances()
                .setInstanceId(instanceId)
                .setWebRtcToken(phoneAccount.getPhoneNo());
        phoneInstancesMapper.insert(phoneInstances);

//		等待实例启动，并操作到验证码停止。并弹出验证码的界面

        String ipAddress = "未获取";
        for (int i = 0; i < 10; i++) {
            Result<Object> error = getObjectResult(3000);
            if (error != null){
                phoneAccountLogInsert("等三秒抛出异常",phoneAccountTask);
                break;
            }
            ipAddress = getIpAddress(phoneAccountTask, instanceId, i);
            if(!(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取") )  ){
                break;
            }
        }
//		10次30秒后还是没获取到IP结束。
        if(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取")){
            phoneAccountLogInsert("获取EIP失败.开始回滚...",phoneAccountTask);
            phoneService.doDeleteInstances(instanceId);
            phoneAccountLogInsert("创建登录盘失败",phoneAccountTask);

            phoneAccountTaskMapper.updateById(phoneAccountTask
                    .setTaskStatus(TaskEnums.TaskStatus.FAIL.getName()));
            return   "未获取到IP，任务失败请检查日志。"   ;
        }
        phoneInstancesMapper.updateById(phoneInstances.setIpAddr(ipAddress));
        System.out.println(phoneInstances.getIpAddr());

        sleepSecond(40000,phoneAccountTask);


//1、
        phoneAccountLogInsert("" + phoneAccount.getPhoneNo() + "打开抖推猫",phoneAccountTask);
        doCommand(2000,"input keyevent  3","按home",instanceId);
        doCommand(2000,"input swipe 300 800 300 80","上滑动",instanceId);
        doCommand(2000,"input tap 489 219","点击逗猫",instanceId);

        phoneAccountLogInsert("2、搜索关键字" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);
        String searchKey = "美女,动漫,游戏".split(",")[ RandomUtil.randomInt(0,2)];

        doCommand(2000,"input tap 300 155","点击搜索框",instanceId);
        doCommand(4000,"input tap 300 155","点击搜索框",instanceId);
        doCommand(2000,"input text  " + searchKey ,"输入文字",instanceId);
        doCommand(2000,"input tap 640 166","点击搜索框",instanceId);


//        doCommand(6000,"input keyevent  3","按home",instanceId);
//        doCommand(6000,"input swipe 300 800 300 80","上滑动",instanceId);
//        doCommand(6000,"input tap 489 219","点击逗猫",instanceId);
        phoneAccountLogInsert("3、点击推广链接" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);
        doCommand(2000,"input tap 625 509","点击二维码",instanceId);
        phoneAccountLogInsert("4、下载链接码" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);
        phoneAccountLogInsert("截图中",phoneAccountTask);
        String url1 ="screen/"+ phoneAccount.getPhoneNo() +"/" +System.currentTimeMillis() +".png";
        doCommand(5000,"screencap -p /sdcard/screen.png","截图",instanceId);
        sleepSecond(3000,phoneAccountTask);
        phoneService.doFetchFile(instanceId,     url1,"/sdcard/screen.png");
//        doCommand(10000,"rm /sdcard/screen.png -f","删除截图",instanceId);
        phoneAccountLogInsert("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url1,phoneAccountTask);
        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setImg("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url1));
        phoneAccountLogInsert("5、下载链接码" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);

        phoneAccountLogInsert("6、打开抖音扫一扫" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);
        String cmdStr ="am start com.ss.android.ugc.aweme/.main.MainActivity";
        String runCommandResult = phoneService.doRunCommand(instanceId, cmdStr);

        doCommand(10000,"input tap 248 839","点击扫描",instanceId);
        doCommand(10000,"input tap 41 69","点击扫描",instanceId);
        phoneAccountLogInsert("7、扫描相册的码" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);

        phoneAccountLogInsert("8、发布小程序" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);

        phoneAccountLogInsert("9、上传视频作品到成功" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);



        phoneAccountLogInsert("截图中",phoneAccountTask);
        String url2 ="screen/"+ phoneAccount.getPhoneNo() +"/" +System.currentTimeMillis() +".png";
        doCommand(5000,"screencap -p /sdcard/screen.png","截图",instanceId);
        sleepSecond(3000,phoneAccountTask);
        phoneService.doFetchFile(instanceId,     url2,"/sdcard/screen.png");
        doCommand(10000,"rm /sdcard/screen.png -f","删除截图",instanceId);
        phoneAccountLogInsert("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url2,phoneAccountTask);

        doCommand(5000,"am force-stop com.doutui.bozhong","关闭抖猫",instanceId);
        sleepSecond(10000,phoneAccountTask);
//        https://cloudphone.console.aliyun.com/?_console_base_disable_=TOP~TOOLKIT#/connectWebRTC?instanceId=cp-bp112zfukuketxa7k7rg&regionId=cn-hangzhou
        phoneAccountLogInsert("本次任务完成。" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);




        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setTaskStatus(TaskEnums.TaskStatus.COMPLETED.getName()));
        return "";
    }

    @Override
    public String clickXCX(PhoneAccountTask phoneAccountTask)   {

        PhoneAccount phoneAccount = phoneAccountMapper.selectOne(
                new QueryWrapper<PhoneAccount>()
                        .eq("id", phoneAccountTask.getAccountId())
        );
        phoneAccountLogInsert("开始点击小程序任务.",phoneAccountTask);

//        创建手机实例
        String instances = phoneService.doRunInstances(new PhoneOrderPamarsVo()
                .setAmount(1)
                .setImageId(phoneAccount.getImgId())
                .setChargeType("PostPaid")
                .setDescription("T" + phoneAccount.getPhoneNo() + "的glj盘")
                .setInstanceName("T" + phoneAccount.getPhoneNo() + "glj")
                .setInstanceType("ecp.ce.large")
                .setKeyPairName("homePhone")
                .setRegionId("cn-hangzhou")
                .setSecurityGroupId("sg-bp1ggdbov2o3nvybkoey")
                .setVSwitchId("vsw-bp1f5diq3vbh9dw4frryq")
        );
        String instanceId = JSON.parseObject(instances).getJSONObject("instanceIds")
                .getJSONArray("instanceId").get(0).toString();
        phoneAccountLogInsert("购买云手机实例完成，实例启动中...",phoneAccountTask);

//        添加创建的实例到实例表
        PhoneInstances phoneInstances = new PhoneInstances()
                .setInstanceId(instanceId)
                .setWebRtcToken(phoneAccount.getPhoneNo());
        phoneInstancesMapper.insert(phoneInstances);

//		等待实例启动，并操作到验证码停止。并弹出验证码的界面

        String ipAddress = "未获取";
        for (int i = 0; i < 10; i++) {
            Result<Object> error = getObjectResult(3000);
            if (error != null){
                phoneAccountLogInsert("等三秒抛出异常",phoneAccountTask);
                break;
            }
            ipAddress = getIpAddress(phoneAccountTask, instanceId, i);
            if(!(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取") )  ){
                break;
            }
        }
//		10次30秒后还是没获取到IP结束。
        if(StringUtil.isBlank(ipAddress) ||  ipAddress.equals("未获取")){
            phoneAccountLogInsert("获取EIP失败.开始回滚...",phoneAccountTask);
            phoneService.doDeleteInstances(instanceId);
            phoneAccountLogInsert("创建登录盘失败",phoneAccountTask);

            phoneAccountTaskMapper.updateById(phoneAccountTask
                    .setTaskStatus(TaskEnums.TaskStatus.FAIL.getName()));
            return   "未获取到IP，任务失败请检查日志。"   ;
        }
        phoneInstancesMapper.updateById(phoneInstances.setIpAddr(ipAddress));
        System.out.println(phoneInstances.getIpAddr());



        phoneAccountLogInsert("1、打开抖音搜索框" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);
        String cmdStr ="am start com.ss.android.ugc.aweme/.main.MainActivity";
        String runCommandResult = phoneService.doRunCommand(instanceId, cmdStr);
        sleepSecond(100000,phoneAccountTask);
        doCommand(5000,"input tap 680 72","点击搜索按钮去搜索页面",instanceId);
        doCommand(5000,"input tap 205 75","点击搜索按钮框",instanceId);
        doCommand(5000,"input text  huahaitucexiaochengxu "     ,"输入文字",instanceId);
        doCommand(5000,"input tap 177 141","点击搜索按钮",instanceId);
        doCommand(5000,"input tap 680 77","点击搜索按钮",instanceId);
        doCommand(5000,"input tap 640 370","点击搜索小程序按钮",instanceId);
        doCommand(5000,"input tap 218 492","点击口令框",instanceId);
        doCommand(5000,"input text " + phoneAccountTask.getTxt()     ,"输入口令",instanceId);
        doCommand(5000,"input tap 640 491","点击口令搜索",instanceId);
        doCommand(5000,"input tap 141 834","点击第一张图",instanceId);
        doCommand(5000,"input tap 645 802","点击下载",instanceId);
        doCommand(5000,"input tap 378 804","点击广告",instanceId);
        doCommand(60000,"input tap 681 81","点击关闭离开",instanceId);


        phoneAccountLogInsert("截图中",phoneAccountTask);
        String url1 ="screen/"+ phoneAccount.getPhoneNo() +"/" +System.currentTimeMillis() +".png";
        doCommand(5000,"screencap -p /sdcard/screen.png","截图",instanceId);
        sleepSecond(3000,phoneAccountTask);
        phoneService.doFetchFile(instanceId,     url1,"/sdcard/screen.png");
        doCommand(10000,"rm /sdcard/screen.png -f","删除截图",instanceId);
        phoneAccountLogInsert("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url1,phoneAccountTask);
        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setImg("https://ylphone.oss-cn-hangzhou.aliyuncs.com/"+ url1));
        doCommand(5000,"am force-stop com.ss.android.ugc.aweme","关闭抖音",instanceId);

        phoneAccountLogInsert("本次任务完成。" + phoneAccount.getPhoneNo() + "-",phoneAccountTask);


        phoneAccountTaskMapper.updateById(phoneAccountTask
                .setTaskStatus(TaskEnums.TaskStatus.COMPLETED.getName()));
        return "";
    }




    @Override
    public String clickAddDevice(PhoneAccountTask phoneAccountTask)   {
//        TaskEnums.TaskStatus.
        return "";
    }




























    private void doCommand(Integer s , String cmdStr, String cmdDesc, String instanceId) {
        getObjectResult(s);
        String runCommandResult = phoneService.doRunCommand(instanceId, cmdStr);
        System.out.println(cmdDesc + "---" + runCommandResult);
    }

    private void sleepSecond(Integer s , PhoneAccountTask phoneAccountTask) {
        Result<Object> error = getObjectResult(s);
        if (error != null){
            phoneAccountLogInsert("sleep抛出异常", phoneAccountTask);
        }
    }

    private void phoneAccountLogInsert(String msg,PhoneAccountTask phoneAccountTask) {
        phoneAccountLogMapper.insert(
                new PhoneAccountLog()
                        .setAccountId(phoneAccountTask.getId())
                        .setLogMsg(msg)
        );
    }


    @Nullable
    private Result<Object> getObjectResult(Integer s) {
        try {
            sleep(s);
        } catch (InterruptedException e) {
            return Result.error("等待实例启动时故障。");
        }
        return null;
    }

    private String getIpAddress(PhoneAccountTask phoneAccountTask, String instanceId, int i ) {
        String status = "启动中";
        String ipAddress = "未获取";
        String instancesInfoBody = phoneService.doListInstances(instanceId);
//        phoneAccountLogInsert(instancesInfoBody, phoneAccount);
        System.out.println( instancesInfoBody );
        System.out.println( "-----------------------------------------" );
        try {
            JSONObject instances2 =  JSON.parseObject(instancesInfoBody)
                    .getJSONObject("instances")
                    .getJSONArray("instance")
                    .getJSONObject(0);
            status = instances2.getString("status");
            ipAddress = instances2.getJSONObject("eipAddress").getString("ipAddress");

        }catch (Exception e){
            System.out.println("检查实例的状态为："+ status +",IP:"+ ipAddress);
        }
        finally {
            phoneAccountLogInsert("第"+(i +1)+"次检查实例的状态为："+ status +",IP:"+ ipAddress, phoneAccountTask);
        }
        return ipAddress;
    }

}
